#define DIR_1 8 //方向信号
#define PUL_1 9//脉冲信号

#define DIR_2 10//方向信号
#define PUL_2 11 //脉冲信号

void setup() {
  //引脚初始化
  pinMode(DIR_1, OUTPUT);
  pinMode(PUL_1, OUTPUT);
  pinMode(DIR_2, OUTPUT);
  pinMode(PUL_2, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0){
    delay(100);
    char buffer;
    buffer=char(Serial.read());

    //两根螺杆上升
    if(buffer=='1'){
      while(1){
        Descend();
        Rise();

        char buffer1;
        buffer1=char(Serial.read());
        if(buffer1=='2'){
          break;
        }
      }
    }
    if(buffer=='3'){
      Rise_0();
    }
    if(buffer=='4'){
      Descend_0();
    }
    
    if(buffer=='5'){
      Descend_0();
      Rise_0();
      Serial.println('5');
    }

  }
}

//螺杆上升函数
void Descend(){
  digitalWrite(DIR_1,LOW);//反转
  digitalWrite(DIR_2,LOW);//反转
  maichong(3000,300);
}

//螺杆下降函数
void Rise(){
  digitalWrite(DIR_1,HIGH);//正转
  digitalWrite(DIR_2,HIGH);//正转
  maichong(3000,300);
}

void Descend_0(){
  digitalWrite(DIR_1,LOW);//反转
  digitalWrite(DIR_2,LOW);//反转
  maichong(2000,300);
}

//螺杆下降函数
void Rise_0(){
  digitalWrite(DIR_1,HIGH);//正转
  digitalWrite(DIR_2,HIGH);//正转
  maichong(2000,300);
}

//螺杆转速及转动距离的函数
void maichong(int times,int speed)//times是脉冲的数量，speed是脉冲间隔，对应着电机的速度
{
  for(int x=0; x<times; x++)
  {
    digitalWrite(PUL_1,HIGH);
    digitalWrite(PUL_2,HIGH);
    delayMicroseconds(500);//这个函数单位为微秒
    digitalWrite(PUL_1,LOW);
    digitalWrite(PUL_2,LOW);
    delayMicroseconds(500);//驱动器说明书规定了脉冲信号的持续时间，在规定的时间内选择尽量小的数值
    delayMicroseconds(speed);
  }
}